package br.ufpe.cin.msc.jrsj2.recommender.resource;

import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

import br.ufpe.cin.msc.jrsj2.recommender.Message;
import br.ufpe.cin.msc.jrsj2.recommender.message.ClientProfile;
import br.ufpe.cin.msc.jrsj2.recommender.message.ClientQuit;
import br.ufpe.cin.msc.jrsj2.recommender.message.ProgramList;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.ClientDAO;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.DAOFactory;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.domain.Client;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.domain.Profile;

public class ProgramServerResource extends ServerResource {

	@Post
	public String requestHandler(String message) {
		String response = null;

		System.out.println(message);
		System.out.println(message);
		System.out.println(message);
		switch (Message.getMessageType(message)) {
		case PROGRAM_LIST:
			ProgramList programList = new ProgramList();

			try {
				programList.buildProgramList(message);

				Client client = new Client(programList.getClientHash(),
						programList.getPrograms());
				ClientDAO clientDAO = DAOFactory.getDAOFactory().getClientDAO();

				if (clientDAO.findById(client.getId()) == null) {
					clientDAO.create(client);
				}

				response = client.getId();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case CLIENT_PROFILE:
			ClientProfile clientProfile = new ClientProfile();
			try {
				clientProfile.buildClientProfile(message);

				ClientDAO clientDAO = DAOFactory.getDAOFactory().getClientDAO();

				Profile profile = new Profile(clientDAO.findById(clientProfile
						.getClientId()), clientProfile.getPrograms());
				// TODO Run recommendation algorithm
				// Preferentially a content-based algorithm
				// To simplify the implementation
				response = "<recomendations>...</recomendations>";
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case CLIENT_QUIT:
			try {
				DAOFactory.getDAOFactory().getClientDAO()
						.remove(ClientQuit.getClientId(message));
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case UNDEFINED:
			break;
		}

		System.out.println(response);
		return response;
	}
}
